<template>
  <div>
    <div class="top" id="top">
      <!--头部bar-->
      <div class="top-bar">
        <div class="w1230 top-main">
          <RouterLink to="/">
            <i class="fa fa-shopping-cart"></i>爱购网首页
          </RouterLink>
          <div class="account">
            <span>{{ loginUser.userName }}<i class="fa fa-caret-down"></i></span>
            <div class="manage">
              <ul>
                <li><a href="../deliverAddress">收货地址</a></li>
                <li><a href="../shoppingCart">我的购物车</a></li>
                <li><a href="/order">我的订单</a></li>
                <li><a v-if="loginUser!=null" href="" @click="logout">退出</a></li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="w1230">
      <img src="../assets/img/logo.png" width="100" height="40" class="logo"/>
      <span class="cart">收货地址</span>
    </div>
    <!--编辑收货地址-->
    <div class="w1230">
      <h3 class="add-title">新增收货地址</h3>
      <div class="add-address">
        <el-form :model="dialogVisible" ref="newAddressForm" label-width="120px">
          <el-form-item label="收货地址">
            <el-input v-model="ReceivingAddressQuery.receivingAddress" placeholder="请输入详细地址"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="ReceivingAddressQuery.mobilePhone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="收件人">
            <el-input v-model="ReceivingAddressQuery.receivingPerson" placeholder="请输入收件人姓名"></el-input>
          </el-form-item>
          <el-form-item label="用户ID" v-show="false">
            <el-input v-model="loginUser.userId"></el-input>
          </el-form-item>

          <p class="chk-address">
            <input type="checkbox" v-model="isDefault" :true-value="1" :false-value="-1" id="setDefaultAddress"
                   @click="setAsDefaultAddress"/>
            <span>设置为默认收货地址</span>
          </p>
          <el-form-item>
            <el-button type="primary" @click=" addReceivingAddressSubmit">保存</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="add-list w1230">
            <p class="message"><i class="fa fa-exclamation-circle"></i>只能保存5个地址</p>
      <table class="table-list">
        <tr>
          <th class="t-id">ID</th>
          <th class="t-address">收货地址</th>
          <th class="t-name">收件人</th>
          <th class="userId">账号</th>
          <th class="mobilePhone">手机号码</th>
          <th class="t-operate">操作</th>
          <th class="t-default">默认地址</th>
        </tr>
        <tr v-for="address in receiveaddress" :key="address.id">
          <td>{{ address.id }}</td>
          <td>{{ address.receivingAddress }}</td>
          <td>{{ address.receivingPerson }}</td>
          <td>{{ address.userId }}</td>
          <td>{{ address.mobilePhone }}</td>

          <!--          <td><a  type="success" @click="editView">修改</a>|<a type="danger" @click="delUser">删除</a></td>
          -->
          <td>
            <a href="javascript:void(0);" @click="editView(address.id)" class="edit-link">修改</a> |
            <a href="javascript:void(0);" @click="delUser(address.id)" class="delete-link">删除</a>
          </td>
          <td>
            <span v-if="address.isDefault ===1 " class="default-on">默认收货地址</span>
            <a v-else href="#" @click="setDefaultAddress(address)">设为默认</a>
          </td>
        </tr>
      </table>
    </div>

    <el-pagination style="justify-content: center;margin-top: 10px"
                   background
                   layout="prev, pager,next"
                   :page-size=pageSize
                   :total=total
                   @current-change="toPage"
                   @prev-click="toPage"
                   @next-click="toPage"
    />
    <el-dialog v-model="dialogVisible" width="1000px"
               :title="ReceivingAddressQuery.id !=null ? '地址详情' : '新增收货地址'"
               draggable="true" center>
      <el-form-item label="收货地址：" prop="receivingAddress">
        <el-input type="text" v-if="ReceivingAddressQuery.id==null" v-model="ReceivingAddressQuery.receivingAddress"/>

        <span class="detail" v-else>{{ ReceivingAddressQuery.receivingAddress }}</span>
      </el-form-item>
      <el-form-item label="手机号：" prop="mobilePhone">
        <el-input type="text" v-if="ReceivingAddressQuery.id==null" v-model="ReceivingAddressQuery.mobilePhone"/>

        <span class="detail" v-else>{{ ReceivingAddressQuery.mobilePhone }}</span>
      </el-form-item>

      <el-form-item label="账号：" prop="userId">
        <el-input type="text" v-if="ReceivingAddressQuery.id==null" v-model="ReceivingAddressQuery.userId"/>

        <span class="detail" v-else>{{ ReceivingAddressQuery.userId }}</span>
      </el-form-item>
      <el-form-item label="默认收货地址：" prop="isDefault">
        <el-input type="text" v-if="ReceivingAddressQuery.id==null" v-model="ReceivingAddressQuery.isDefault"/>

        <span class="detail" v-else>{{ ReceivingAddressQuery.isDefault }}</span>
      </el-form-item>
      <el-form-item label="收件人：" prop="receivingPerson">
        <el-input type="text" v-if="ReceivingAddressQuery.id==null" v-model="ReceivingAddressQuery.receivingPerson"/>

        <span class="detail" v-else>{{ ReceivingAddressQuery.receivingPerson }}</span>
      </el-form-item>

    </el-dialog>
    <el-dialog v-model="editDialogVisible" width="1000px" draggable="true" center>
      <el-form ref="addRefForm" :model="editReceivingAddressQuery" label-width="auto" style="max-width: 800px">
        <el-form-item label="收货地址：" prop="receivingAddress">
          <el-input v-model="editReceivingAddressQuery.receivingAddress"/>
        </el-form-item>
        <el-form-item label="收件人：" prop="receivingPerson">
          <el-input v-model="editReceivingAddressQuery.receivingPerson"/>
        </el-form-item>
        <el-form-item label="手机号：" prop="mobilePhone">
          <el-input v-model="editReceivingAddressQuery.mobilePhone"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editReceivingAddressSubmit">
            确定
          </el-button>

        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";
export default {
  name: "ReceivingAddressView",
  data() {
    return {
      isDefault: -1,
      ReceivingAddressList: [],
      dialogVisible: false,
      ReceivingAddressQuery: {},
      Address:{},
      editReceivingAddressQuery: {},
      total: 0,
      editDialogVisible: false,
      pageSize: 5, // 假设每页显示10条数据
      receivingaddressOptions: [{}],
      idArray: [],
      loginUser: {},
      receiveaddress: [],
      // 移除不必要的选项，因为我们不需要在收货地址列表中显示它们
    };
  },
  mounted() {

    this.selectUserId(this.loginUser.userId);
    // this.selectUserId(1);

    this.loginUser = JSON.parse(localStorage.getItem("user"));
    console.log(this.loginUser);
    if (this.loginUser && this.loginUser.userId) {
      this.selectUserId(this.loginUser.userId);
    }
  },
  methods: {
    setAsDefaultAddress() {
      // 切换 isDefault 的值
      this.isDefault = this.isDefault === 1 ? -1 : 1;
      console.log(this.isDefault)
    },
    checkDuplicateAddress() {
      return new Promise((resolve, reject) => {
        // 发送请求到后端检查地址是否重复
        // 假设后端API为 /user/receivingaddress/checkDuplicate
        doGet("/user/receivingaddress/checkDuplicate", {
          receivingAddress: this.ReceivingAddressQuery.receivingAddress,
          mobilePhone: this.ReceivingAddressQuery.mobilePhone,
          receivingPerson: this.ReceivingAddressQuery.receivingPerson
        }).then(resp => {
          if (resp.data.isDuplicate) {
            resolve(true); // 地址重复
          } else {
            resolve(false); // 地址不重复
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    addReceivingAddressSubmit() {
      if (this.receiveaddress.length >= 5) {
        messageTip("您最多只能设置5条收货地址", "error");
        return; // 如果已达到限制，则不执行后续操作
      }
      this.ReceivingAddressQuery.userId = this.loginUser.userId;
      this.ReceivingAddressQuery.isDefault = this.isDefault;

      doPost("/user/receivingaddress/usersave", this.ReceivingAddressQuery).then((resp) => {
        if (resp.data.code === 200) {
          this.dialogVisible = false;
          messageTip("添加成功", "success");
          this.selectUserId(this.loginUser.userId);
        } else {
          messageTip("添加失败", "error");
        }
      });

    },
    setDefaultAddress(address){
      this.Address.userId = this.loginUser.userId;
      this.Address.isDefault = 1;
      this.Address.receivingAddress=address.receivingAddress;
      this.Address.receivingPerson=address.receivingPerson;
      this.Address.id=address.id;
      this.Address.mobilePhone=address.mobilePhone;
      doPut("/user/receivingaddress/isDefault/", this.Address ).then((resp)=>{
        if(resp.data.code ===200){
          messageTip("修改成功！", "success");
          this.selectUserId(this.loginUser.userId);
        }
      })
    },
    editReceivingAddressSubmit() {
      doPut("/user/receivingaddress/edit/", this.editReceivingAddressQuery).then((resp) => {
        if (resp.data.code === 200) {
          this.editDialogVisible = false;
          messageTip("修改成功！", "success");
          this.selectUserId(this.loginUser.userId);
        }
      });
    },
    toPage(current) {
      this.selectUserId(current);
    },
    logout() {
      this.loginUser = null
      localStorage.removeItem("user");
      this.$router.push("/");
    },
    formatter(row, column) {
      return row.address;
    },
    // view(id) {
    //   doGet("/receivingaddress/" + id).then((resp) => {
    //     if (resp.data.code === 200) {
    //       this.ReceivingAddressQuery = resp.data.data;
    //       this.dialogVisible = true;
    //     }
    //   });
    // },
    delUser(id) {
      messageConfirm("是否删除该收货地址？").then(() => {
        doDelete("/user/receivingaddress/" + id).then((resp) => {
          if (resp.data.code === 200) {
            messageTip("删除成功!", "success");
            this.selectUserId(this.loginUser.userId);
          }
        });
      });
    },

    onReset() {
      this.ReceivingAddressQuery = {
        receivingAddress: '',
        mobilePhone: '',
        receivingPerson: '',
        isDefault: false
      };
    },
    selectUserId(userId) {
      doGet("/user/receivingaddress/user/" + userId).then((resp) => {
        if (resp.data.code === 200) {
          this.pageSize = resp.data.data.pageSize
          this.receiveaddress = resp.data.data;
          console.log(this.receiveaddress);
        } else {
          // 处理错误情况，例如显示错误消息
          console.error("Failed to fetch receiving addresses:", resp.data.message);
        }
      }).catch((error) => {
        // 处理网络错误或其他请求错误
        console.error("Error fetching receiving addresses:", error);
      });
    },
    editView(id) {
      doGet("/user/receivingaddress/" + id).then((resp) => {
        if (resp.data.code === 200) {
          this.editReceivingAddressQuery = resp.data.data;
          this.editDialogVisible = true;
        }
      });
    },


  }
};
</script>

<style scoped>
@import "../assets/css/reset.css";
@import "../assets/css/top.css";
@import "../assets/css/deliverAddress.css";
@import "../assets/css/font-awesome-4.7.0/Font-Awesome-master/css/font-awesome.min.css";

.add-list {
  width: 100%; /* 或者设置一个具体的宽度，比如 80% */
  margin: 0 auto; /* 这将使 .add-list 在其父容器中水平居中 */
  text-align: center; /* 这将影响表格内的文本对齐，但通常我们不需要对表格整体使用这个 */
}

.table-list {
  margin: 0 auto; /* 如果 .add-list 已经是居中的，这一行可能不是必需的 */
  width: 78%; /* 或者设置一个具体的宽度，确保不要超出 .add-list */
  /* 其他表格样式 */
}

/* 确保表格内的内容（如文本和链接）按需要的方式对齐 */
.table-list th, .table-list td {
  text-align: left; /* 或者 center, right，根据需要设置 */
  padding: 10px; /* 添加一些内边距使内容不会紧贴边框 */
}

/* 如果需要，为“操作”和“默认地址”列设置特定的对齐方式 */
.t-operate, .t-default {
  text-align: center; /* 例如，使这些列的内容居中 */
}

.message {
  width: 78%; /* 或者你想要的任何宽度 */
  margin: 0 auto; /* 水平居中 */
  text-align: center; /* 可选，如果你还想要文本在元素内居中 */
}

.chk-address {
  margin-top: -15px; /* 调整这个值以控制移动的距离 */
}

.checked {
  font-weight: bold;
  color: blue; /* 或者你喜欢的任何颜色 */
}
</style>
